const {
  GiftShopModel
} = require('../../../utils/giftshop-model.js')
const giftShopModel = new GiftShopModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIdx: 0,
    navigateCode: '',
    classify: [],
    classifySeconds: []
  },

  goSearch(e) {
    const item = e.currentTarget.dataset.item
    wx.reportAnalytics('goodsclassify_category');
    wx.navigateTo({
      url: `/pages/giftShop/classifySearch/index?name=${item.navigateName}&navigateCode=${item.navigateCode}`
    })
  },

  menuChange(e) {
    wx.reportAnalytics('goodsclassify_menu');
    const index = e.currentTarget.dataset.index
    this.setData({
      activeIdx: index,
      classifySeconds: this.data.classify[index].childs || []
    })
  },

  getClassify() {
    const merchantId = wx.getStorageSync('merchantId')
    giftShopModel.getClassify({
      merchantId
    }).then(data => {
      let defaultIdx = 0;
      (data || []).forEach((item, index) => {
        if (item.navigateCode === this.data.navigateCode) {
          defaultIdx = index
        }
      })
      this.setData({
        activeIdx: defaultIdx,
        classify: data || [],
        classifySeconds: (data[defaultIdx] || {}).childs || []
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const navigateCode = options.navigateCode || ''
    this.setData({
      navigateCode
    })
    this.getClassify()
  }
})